<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\admin\controller;

use app\admin\Controller;
use app\common\facade\View;
use app\common\model\Post as Post;
use app\common\validate\PostValidate;
use Xin\Thinkphp5\Controller\CURD;

class ArticleController extends Controller{

	use CURD {
		showCreateView as showCreateView2;
		showUpdateView as showUpdateView2;
	}

	/**
	 * @var string
	 */
	protected $validator = PostValidate::class;

	/**
	 * @var string
	 */
	protected $model = Post::class;

	/**
	 * 文章管理
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function index(){
		$id = $this->request->param('id/d', 0);

		$query = Post::withTrashed();

		if($id > 0){
			$query = $query->where('id', $id);
		}else{
			$categoryId = $this->request->param('category_id/d', 0);
			$keywords = $this->request->keywordsSql();
			$query = $query->when(!empty($keywords), [['title', 'like', $keywords]])
				->when($categoryId > 0, ['category_id' => $categoryId]);
		}

		$data = $query->order('id desc')->paginate($this->request->limit(), false, [
			'page'  => $this->request->page(),
			'query' => $this->request->get(),
		]);

		$this->assign('data', $data);
		$this->assignTreeCategory();
		return View::fetch();
	}

	/**
	 * @inheritDoc
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	protected function showCreateView(){
		$this->assignTreeCategory();
		return $this->showCreateView2();
	}

	/**
	 * @inheritDoc
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	protected function showUpdateView($model){
		$this->assignTreeCategory();
		return $this->showUpdateView2($model);
	}

	/**
	 * 向页面赋值分类列表
	 *
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	private function assignTreeCategory(){
		$data = CategoryController::treeToList();
		$this->assign('categories', $data);
	}

	//	/**
	//	 * 应用标签列表
	//	 */
	//	private function assignBadge(){
	//		$data = BadgeModel::select();
	//		$this->assign('badge_list', $data);
	//	}
}
